<template>
  <div ref="boxwrap" class="history-wrap mt-50">
    <div ref="filterwrap" class="filter-container">
      <el-form ref="form" :inline="true" :model="form" size="small">
        <el-form-item label="制程">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.regionid" placeholder="请选择" class="filter-item" filterable multiple collapse-tags @change="LoadLines()">
              <el-option v-for="item in form.regionArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="线别">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.lineId" placeholder="请选择" class="filter-item" filterable multiple collapse-tags @change="LoadSlots()">
              <el-option v-for="item in form.lineArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="槽/段">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.slotId" placeholder="请选择" class="filter-item" filterable multiple collapse-tags @change="LoadDevices()">
              <el-option v-for="item in form.slotArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="仪表类型">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.devType" placeholder="请选择" class="filter-item" filterable multiple collapse-tags @change="filterDeviceByType">
              <el-option v-for="item in deviceTypeList" :key="item.typeId" :label="item.typeName" :value="item.typeId" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="仪表">
          <el-tooltip class="item" effect="dark" content="可多选" placement="top">
            <el-select v-model="form.devId" placeholder="请选择" class="filter-item" filterable multiple collapse-tags>
              <el-option v-for="item in form.devArr" :key="item.devId" :label="item.devName" :value="item.devId" />
            </el-select>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="时间">
          <el-col :span="11">
            <el-date-picker v-model="form.startTime" type="datetime" placeholder="开始时间" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" @change="handleSearch" />
          </el-col>
          <el-col class="separator" :span="2"> ~ </el-col>
          <el-col :span="11">
            <el-date-picker v-model="form.endTime" type="datetime" placeholder="结束时间" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" @change="handleSearch" />
          </el-col>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-main">
      <div class="table-list">
        <vxe-table
          ref="xTable"
          :loading="listLoading"
          :data="pageList"
          border
          :height="tableHeight"
          :print-config="tablePrint"
          auto-resize
          size="small"
          :seq-config="{startIndex: (pageObj.page - 1) * pageObj.limit}"
        >
          <vxe-column type="seq" title="序号" width="80" />
          <vxe-column v-for="item in tableCol" :key="item.prop" :field="item.prop" :title="item.label" :width="item.width || ''" />
        </vxe-table>

        <pagination :total="pageObj.total" :page-sizes="pageObj.pageSize" :page.sync="pageObj.page" :limit.sync="pageObj.limit" layout="total, sizes, prev, pager, next" @pagination="getPage" />
      </div>

      <div class="operate-btns">
        <el-button type="primary" plain icon="el-icon-search" @click="handleSearch()">查询</el-button>
        <el-button type="primary" plain icon="el-icon-download" @click="downloadTable">导出</el-button>
        <el-button type="primary" plain icon="el-icon-printer" @click="printTable">打印</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { defaultDevType } from '@/api/default-apis'
import { getProcess, getLineByProcess, getSlotByLine, getDeviceBySlot } from '@/api/conf'
import { getHistoryData } from '@/api/reports'
import { parseTime, isValued, idsStr } from '@/utils'
import Pagination from '@/components/Pagination'

export default {
  name: 'HistoryData',
  components: { Pagination },
  data() {
    return {
      tableKey: 0,
      list: [],
      pageList: [],
      listLoading: false,
      deviceTypeList: [],
      deviceTypeObj: {},
      tableHeight: 'auto',
      tableCol: [
        { label: '制程', prop: 'regionName' },
        { label: '线别', prop: 'lineName' },
        { label: '槽/段', prop: 'slotName' },
        { label: '仪表类型', prop: 'devTypeStr', width: '100' },
        { label: '仪表名称', prop: 'devName' },
        { label: '上限', prop: 'upperLimit', width: '100' },
        { label: '下限', prop: 'lowerLimit', width: '100' },
        { label: '当前值', prop: 'dataValue', width: '100' },
        { label: '单位', prop: 'dataUnit', width: '80' },
        { label: '接收时间', prop: 'recTime' }
      ],
      form: {
        regionid: [],
        regionArr: [],
        lineId: [],
        lineArr: [],
        slotId: [],
        slotArr: [],
        devType: [],
        devId: [],
        devArr: [],
        startTime: '',
        endTime: ''
      },
      deviceList: [],
      listQuery: {
        regionid: '',
        lineId: '',
        slotId: '',
        devType: '',
        devId: '',
        startTime: '',
        endTime: ''
      },
      lineQuery: {
        regionid: ''
      },
      soltQuery: {
        lineId: ''
      },
      devQuery: {
        slotId: ''
      },
      devTypes: '',
      pageObj: {
        page: 1, // 第几页
        limit: 20, // 每页条数
        total: 0, // 总条数
        pageSize: [20, 40, 60, 80, 100]
      },
      tablePrint: {
        // 自定义打印的样式
        style: `
                .vxe-table {
                  color: #000000; // 修改表格默认颜色
                  font-size: 12px; // 修改表格默认字体大小
                }
                .vxe-table,
                .vxe-table thead th,
                .vxe-table tbody td,
                .vxe-table tfoot td  {
                  border-color: #000000; // 修改表格边框颜色
                }
                .vxe-table thead th {
                  color: #000000; // 修改表头字体颜色
                  font-size: 14px; // 修改表头默认字体大小
                }
                .vxe-table tfoot td {
                  color: #000000; // 修改表尾字体颜色
                }
                `
      }
    }
  },
  mounted() {
    this.getTableHeight()
  },
  created() {
    this.form.startTime = parseTime(new Date().getTime() - 1000 * 60 * 60) // 提前一小时
    this.form.endTime = parseTime(new Date())
    this.init()
    // this.getList()
  },
  methods: {
    init() {
      defaultDevType().then(res => {
        this.deviceTypeList = [].concat(res)
        this.deviceTypeList.forEach(val => {
          this.deviceTypeObj[val.typeId] = val.typeName
        })
      })
      getProcess().then(res => {
        this.form.regionArr = res.data
        this.LoadLines()
      })
    },
    LoadLines() {
      if (isValued(this.form.regionid)) {
        this.lineQuery.regionid = idsStr(this.form.regionid, 'id', true)
      } else {
        this.lineQuery.regionid = idsStr(this.form.regionArr, 'id', false)
      }
      getLineByProcess(this.lineQuery).then(res => {
        this.form.lineArr = res.data
        this.LoadSlots()
      })
    },
    LoadSlots() {
      if (isValued(this.form.lineId)) {
        this.soltQuery.lineId = idsStr(this.form.lineId, 'id', true)
      } else {
        this.soltQuery.lineId = idsStr(this.form.lineArr, 'id', false)
      }
      getSlotByLine(this.soltQuery).then(res => {
        this.form.slotArr = res.data
        this.LoadDevices()
      })
    },
    LoadDevices() {
      if (isValued(this.form.slotId)) {
        this.devQuery.slotId = idsStr(this.form.slotId, 'id', true)
      } else {
        this.devQuery.slotId = idsStr(this.form.slotArr, 'id', false)
      }
      const query = Object.assign({}, this.lineQuery, this.soltQuery, this.devQuery)
      getDeviceBySlot(query).then(res => {
        this.deviceList = res.data
        this.filterDeviceByType()
      })
    },
    filterDeviceByType() {
      this.form.devArr = []
      if (isValued(this.form.devType)) {
        this.devTypes = this.form.devType.join(',')
        this.deviceList.forEach(item => {
          this.form.devType.forEach(val => {
            if (item.devType === parseInt(val)) {
              this.form.devArr.push(item)
            }
          })
        })
      } else {
        this.devTypes = Object.keys(this.deviceTypeObj).join(',')
        this.form.devArr = this.deviceList
      }
      this.handleSearch()
    },
    isValued(arr) {
      return arr.length > 0
    },
    // 查询
    handleSearch() {
      this.listLoading = true
      let devids = ''
      if (isValued(this.form.devId)) {
        devids = idsStr(this.form.devId, 'devId', true)
      } else {
        devids = idsStr(this.form.devArr, 'devId', false)
      }
      this.listQuery = {
        regionid: this.lineQuery.regionid,
        lineId: this.soltQuery.lineId,
        slotId: this.devQuery.slotId,
        devType: this.devTypes,
        devId: devids,
        startTime: this.form.startTime,
        endTime: this.form.endTime
      }
      // console.log(this.listQuery)
      getHistoryData(this.listQuery).then(res => {
        res.data.map(val => {
          val.devTypeStr = this.deviceTypeObj[val.devType]
          return val
        })
        this.list = res.data
        this.pageObj.total = res.data.length
        this.getPage()
        this.listLoading = false
      }).catch(error => {
        if (error) {
          this.listLoading = false
        }
      })
    },
    getPage() {
      this.pageList = this.list.filter((item, index) => {
        return index < this.pageObj.limit * this.pageObj.page && index >= this.pageObj.limit * (this.pageObj.page - 1)
      })
    },
    indexMethod(index) { // 表格序号方法,翻页后序号连续
      return (index + 1) + (this.pageObj.page - 1) * this.pageObj.limit
    },
    getTableHeight() {
      const that = this
      const dom = this.$refs.boxwrap
      const filterwrap = this.$refs.filterwrap
      this.$erd.listenTo(dom, function(element) {
        that.tableHeight = dom.clientHeight - filterwrap.clientHeight - 50
      })
    },
    downloadTable() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        // 表头str
        const tHeader = ['序号']
        // 表头字段
        const filterVal = ['index']
        this.tableCol.forEach(item => {
          tHeader.push(item.label)
          filterVal.push(item.prop)
        })
        const list = this.list // 未分页的全部数据
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '设备数据' + this.form.startTime + '-' + this.form.endTime
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v, idx) => filterVal.map(j => {
        v.index = idx + 1
        return v[j]
      }))
    },
    printTable() {
      this.$refs.xTable.print({ data: this.list })
    }
  }
}
</script>
<style lang="scss" scoped>
  .history-wrap{
    height: calc(100% - 50px);
  }
  .dialog-form{
    width: 90%;
    margin:0 auto;
  }
  .el-form-item--small.el-form-item{
    margin-bottom: 5px;
  }
</style>
